package com.sea.operate.controller;

import com.codecrane.core.util.DateUtils;
import com.codecrane.core.util.ExcelUtil;
import com.codecrane.core.web.Ajax;
import com.codecrane.core.web.AjaxReturn;
import com.codecrane.core.web.AjaxTableReturn;
import com.codecrane.core.web.BatchImportUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sea.operate.entity.Related;
import com.sea.operate.entity.WordClick;
import com.sea.operate.service.RelatedService;
import com.sea.operate.service.WordClickService;
import com.sea.product.service.ChannelService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 *  控制器
 * @author 陈鸿飞
 *  <br/>
 *  <br/>
 */
@Controller
@RequestMapping("/sea/operate/wordClick")
public class WordClickController {

    @Autowired
    private ChannelService channelService;
    @Autowired
    private RelatedService relatedService;
    @Autowired
    private WordClickService wordClickService;



    /**
     * 管理主页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/main")
    public String main(Model model) {
        model.addAttribute("channel",channelService.findByCnd(null));

        return "/sea/operate/wordClick/main";
    }


    /**
     * 分页条件查询
     *
     * @param pagesize
     * @param start
     * @return
     */
    @ResponseBody
    @RequestMapping("/findByCnd")
    public AjaxTableReturn findByCnd(@RequestParam(value = "limit", defaultValue = "10") int pagesize,
                                     @RequestParam(value = "offset", defaultValue = "0") int start,
                                     WordClick wordClick) {
        start = start > 0 ? start / pagesize + 1 : 1;
        PageHelper.startPage(start, pagesize);
        List<WordClick> relatedList = wordClickService.findByCnd(wordClick);
        PageInfo<WordClick> page = new PageInfo<>(relatedList);
        return Ajax.tableDataOk(page.getTotal(), page.getList());
    }







    /**
     * 保存
     * @param related
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/usave", method = RequestMethod.POST)
    public AjaxReturn usave(Related related) {
        AjaxReturn result = Ajax.fail().setMsg("修改失败！");
        try{
            if (null != related && relatedService.usave(related) > 0) {
                result.setOk(true).setMsg("修改成功！");
            }
        }catch (DuplicateKeyException e){
            result.setMsg("当前Listing不能重复!");
            return result;
        } catch (Exception e){
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }

    /**
     * 导出收货数据
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/export")
    @ResponseBody
    public void export(HttpServletResponse response) throws Exception {
        String basePath = "D:\\asin";
        File dir = new File(basePath);
        List<File> allFileList = new ArrayList<>();
        // 判断文件夹是否存在
        if (!dir.exists()) {
            System.out.println("目录不存在");
            return;
        }
        getAllFile(dir, allFileList);
            for (File file : allFileList) {
                if (file.getName().contains("xlsx") || file.getName().contains("xls")) {
                    FileInputStream input = new FileInputStream(file);
                    Workbook workBook = BatchImportUtils.getWorkBook(input, file.getName());
                    List<Sheet> sheets = BatchImportUtils.getSheets(workBook);
                    if (null != sheets && sheets.size() > 0) {
                        Sheet sheet = sheets.get(0);
                        List<WordClick> list = BatchImportUtils.iteratorForWordClick(sheet);
                        if (null == list || list.size() == 0) {

                        } else {
                            for (WordClick wordClick : list) {
                                try {
                                    wordClickService.save(wordClick);
                                }catch (Exception e){
                                    e.printStackTrace();
                                }

                            }

                        }
                    }
                }
            }

        System.out.println("该文件夹下共有" + allFileList.size() + "个文件");
    }

    //发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(),"ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


    public static void getAllFile(File fileInput, List<File> allFileList) {
        // 获取文件列表
        File[] fileList = fileInput.listFiles();
        assert fileList != null;
        for (File file : fileList) {
            if (file.isDirectory()) {
                // 递归处理文件夹
                // 如果不想统计子文件夹则可以将下一行注释掉
                getAllFile(file, allFileList);
            } else {
                // 如果是文件则将其加入到文件数组中

                allFileList.add(file);
            }
        }
    }



}
